﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;

namespace Awesom_O_Controller
{
    public partial class Main : Form
    {
        readonly AwesomoCoreWatcher _awesomoCoreWatcher = new AwesomoCoreWatcher();
        readonly Dictionary<string, DiabloWatcher> _diabloWatchers = new Dictionary<string, DiabloWatcher>();
        readonly List<string> _diabloDirectoriesInUse = new List<string>();

        public Main()
        {
            InitializeComponent();
        }

        private void AwesomoCoreWatcherCoreCrashed(object sender, EventArgs e)
        {
            _awesomoCoreWatcher.Restart();

            while (!_awesomoCoreWatcher.Running)
                Thread.Sleep(100);

            foreach (KeyValuePair<string, DiabloWatcher> pair in _diabloWatchers.Where(pair => pair.Value.Running))
            {
                pair.Value.Restart();
            }
        }

/*
        private void Reset()
        {
            while (!_awesomoCoreWatcher.Running)
                Thread.Sleep(100);

            foreach (KeyValuePair<string, DiabloWatcher> pair in _diabloWatchers.Where(pair => pair.Value.Running))
            {
                pair.Value.Restart();
            }
        }
*/

        void LogMessageLogged(object sender, EventArgs e)
        {
            string temp = Log.Message;
            temp = temp.Replace("[", "");
            string[] message = temp.Split(Convert.ToChar("]"));
            message[0] = message[0].Remove(0, 11);

            CheckForIllegalCrossThreadCalls = false;
            if (message[1] == "N/A")
                textBoxLog.AppendText(message[0] + " -- " + message[3] + "\n");
            else
                textBoxLog.AppendText(message[0] + " [" + message[1] + "] -- " + message[3] + "\n");
            CheckForIllegalCrossThreadCalls = true;
        }

        private void ButtonStartClick(object sender, EventArgs e)
        {
            if (listViewProfiles.FocusedItem == null) return;

            if (!File.Exists(Application.StartupPath + "\\ControllerSettings\\Awesom-O Core Settings.aoc"))
            {
                new AwesomoCoreConfigurator().ShowDialog();
                if (!File.Exists(Application.StartupPath + "\\ControllerSettings\\Awesom-O Core Settings.aoc"))
                    return;
            }

            string profileName = listViewProfiles.FocusedItem.Text;

            if (_diabloWatchers[profileName].Running) { MessageBox.Show("Profile is already running."); return; }
            if (_diabloDirectoriesInUse.Contains(_diabloWatchers[profileName].Profile.DiabloPath)) { MessageBox.Show("Diablo II directory is already in use."); return; }

            if (!_awesomoCoreWatcher.Running)
            {
                _awesomoCoreWatcher.Start();
                Thread.Sleep(2500);
            }

            _diabloDirectoriesInUse.Add(_diabloWatchers[profileName].Profile.DiabloPath);
            _diabloWatchers.Remove(profileName);
            _diabloWatchers.Add(profileName, new DiabloWatcher(ProfileSettings.GetSettings(profileName)));
            _diabloWatchers[profileName].Start();
        }

        private void ButtonStopClick(object sender, EventArgs e)
        {
            string profileName = listViewProfiles.FocusedItem.Text;

            try { _diabloWatchers[profileName].Stop(); } catch { }

            if (_diabloDirectoriesInUse.Contains(_diabloWatchers[profileName].Profile.DiabloPath))
            {
                _diabloDirectoriesInUse.Remove(_diabloWatchers[profileName].Profile.DiabloPath);
            }
        }

        private static void MainFormClosed(object sender, FormClosedEventArgs e)
        {
            Environment.Exit(0);
        }

        private void MainShown(object sender, EventArgs e)
        {
            _awesomoCoreWatcher.CoreCrashed += AwesomoCoreWatcherCoreCrashed;
            Log.MessageLogged += LogMessageLogged;
            UpdateProfiles();
        }

        private void ButtonNewClick(object sender, EventArgs e)
        {
            new ProfileConfigurator().ShowDialog();
            UpdateProfiles();
        }

        private void ButtonEditClick(object sender, EventArgs e)
        {
            if (listViewProfiles.FocusedItem != null)
            {
                new ProfileConfigurator(ProfileSettings.GetSettings(listViewProfiles.FocusedItem.Text)).ShowDialog();
            }
        }

        private void ButtonDeleteClick(object sender, EventArgs e)
        {
            if (listViewProfiles.FocusedItem == null) return;
            if (MessageBox.Show("Are you sure you want to delete this profile?", "Awesom-O Controller", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                File.Delete(Application.StartupPath + "\\ControllerSettings\\Profiles\\" + (listViewProfiles.FocusedItem.Text) + ".aoc");
                UpdateProfiles();
            }
        }

        private void UpdateProfiles()
        {
            if (!Directory.Exists(Application.StartupPath + "\\ControllerSettings\\Profiles")) return;
            listViewProfiles.Items.Clear();
            string[] profiles = Directory.GetFiles(Application.StartupPath + "\\ControllerSettings\\Profiles");
            foreach (string s in profiles)
            {
                string profile = s;
                profile = profile.Remove(0, profile.LastIndexOf(Convert.ToChar("\\")) + 1);
                profile = profile.Remove(profile.IndexOf(Convert.ToChar(".")));
                listViewProfiles.Items.Add(profile);

                if (!_diabloWatchers.ContainsKey(s))
                {
                    _diabloWatchers.Add(profile, new DiabloWatcher(ProfileSettings.GetSettings(profile)));
                }
            }
        }

        private void MainFormClosing(object sender, FormClosingEventArgs e)
        {
            try 
            {
                foreach (KeyValuePair<string, DiabloWatcher> pair in _diabloWatchers)
                {
                    _diabloWatchers[pair.Key].Stop();
                }
            }
            catch { }
            try { _awesomoCoreWatcher.Stop(); }
            catch { }
        }

        private static void ButtonAwesomoCoreSettingsClick(object sender, EventArgs e)
        {
            new AwesomoCoreConfigurator().ShowDialog();
        }
    }
}
